import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue')
  },
  {
    path: '/test',
    name: 'test',
    component: () => import('@/views/TestView.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    children: [
      {
        path: 'userinfo',
        name: 'userinfo',
        component: () => import('@/views/userinfo/UserinfoList.vue')
      },
      {
        path: 'teacher',
        name: 'teacher',
        component: () => import('@/views/teacher/TeacherList.vue')
      },
      {
        path: 'role',
        name: 'role',
        component: () => import('@/views/role/RoleList.vue')
      },
      {
        path: 'banner',
        name: 'banner',
        component: () => import('@/views/banner/BannerList.vue')
      },
      {
        path: 'enterprise',
        name: 'enterprise',
        component: () => import('@/views/enterprise/EnterpriseEdit.vue')
      },
      {
        path: 'project',
        name: 'project',
        component: () => import('@/views/project/ProjectList.vue')
      },
      {
        path: 'school',
        name: 'school',
        component: () => import('@/views/school/SchoolList.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const whiteSheet = ['/', '/login']
  let isWhite = false
  for (const ws of whiteSheet) {
    if (ws === to.path) {
      isWhite = true
      break
    }
  }
  if (isWhite) {
    next()
  } else {
    if (Vue.prototype.$cookies.get('token')) {
      next()
    } else {
      Vue.prototype.$alert('token失效，请重新登录！', { type: 'error' }).then(() => {
        Vue.prototype.$cookies.remove('token')
        next('/')
      })
    }
  }
})

export default router
